package com.buaa.aimall.computeModule.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buaa.aimall.computeModule.Entity.ComputeEntity;
import com.buaa.aimall.Utils.Exception.BusinessException;
import com.buaa.aimall.computeModule.Mapper.ComputeMapper;
import com.buaa.aimall.Utils.MinioUtils;
import com.buaa.aimall.userModule.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.buaa.aimall.computeModule.DTO.FilterComputeDTO;
import com.buaa.aimall.Utils.PageReturnResult;
import com.buaa.aimall.computeModule.Enum.ComputeSortTypeEnum;

import java.util.UUID;
import java.util.List;

@Service
public class ComputeServiceImpl extends ServiceImpl<ComputeMapper, ComputeEntity> implements ComputeService {

    @Autowired
    private UserService userService;

    @Autowired
    private MinioUtils minioUtils;

    @Override
    public Boolean createCompute(ComputeEntity computeEntity, MultipartFile docFile) {
        if (docFile != null && !docFile.isEmpty()) {
            try {
                String randomString = UUID.randomUUID().toString();
                String fileName = "compute_helper_document/" + randomString + "_" + docFile.getOriginalFilename();
                minioUtils.upload(docFile, fileName);
                computeEntity.setDocURL(fileName);
            } catch (Exception e) {
                throw new BusinessException("计算资源文档上传失败: " + e.getMessage());
            }
        }
        if (computeEntity.getIsEnable() == null) {
            computeEntity.setIsEnable(true);
        }
        computeEntity.setDelFlag(0);
        return this.save(computeEntity);
    }

    @Override
    public PageReturnResult<ComputeEntity> filterCompute(FilterComputeDTO filterComputeDTO) {
        PageReturnResult<ComputeEntity> result = new PageReturnResult<>();
        LambdaQueryWrapper<ComputeEntity> queryWrapper = new LambdaQueryWrapper<>();
        Integer pageSize = filterComputeDTO.getPageSize();
        Integer currentPage = filterComputeDTO.getCurrentPage();


        // 根据 FilterComputeDTO 中的字段动态构建查询条件
        if (filterComputeDTO.getId() != null)
            queryWrapper.eq(ComputeEntity::getId, filterComputeDTO.getId());
        if (filterComputeDTO.getName() != null)
            queryWrapper.like(ComputeEntity::getName, filterComputeDTO.getName());
        if (filterComputeDTO.getType() != null)
            queryWrapper.like(ComputeEntity::getType, filterComputeDTO.getType());
        if (filterComputeDTO.getFk_creator() != null)
            queryWrapper.like(ComputeEntity::getCreator, filterComputeDTO.getFk_creator());

        // 时间范围查询
        if (filterComputeDTO.getCreate_time_start() != null)
            queryWrapper.ge(ComputeEntity::getCreateTime, filterComputeDTO.getCreate_time_start());
        if (filterComputeDTO.getCreate_time_end() != null)
            queryWrapper.le(ComputeEntity::getCreateTime, filterComputeDTO.getCreate_time_end());
        if (filterComputeDTO.getUpdate_time_start() != null)
            queryWrapper.ge(ComputeEntity::getUpdateTime, filterComputeDTO.getUpdate_time_start());
        if (filterComputeDTO.getUpdate_time_end() != null)
            queryWrapper.le(ComputeEntity::getUpdateTime, filterComputeDTO.getUpdate_time_end());

        // 内存大小范围查询
        if (filterComputeDTO.getMemory_size_min() != null)
            queryWrapper.ge(ComputeEntity::getMemorySize, filterComputeDTO.getMemory_size_min());
        if (filterComputeDTO.getMemory_size_max() != null)
            queryWrapper.le(ComputeEntity::getMemorySize, filterComputeDTO.getMemory_size_max());

        // 价格范围查询
        if (filterComputeDTO.getPrice_by_hour_min() != null)
            queryWrapper.ge(ComputeEntity::getPriceByHour, filterComputeDTO.getPrice_by_hour_min());
        if (filterComputeDTO.getPrice_by_hour_max() != null)
            queryWrapper.le(ComputeEntity::getPriceByHour, filterComputeDTO.getPrice_by_hour_max());
        if (filterComputeDTO.getPrice_by_day_min() != null)
            queryWrapper.ge(ComputeEntity::getPriceByDay, filterComputeDTO.getPrice_by_day_min());
        if (filterComputeDTO.getPrice_by_day_max() != null)
            queryWrapper.le(ComputeEntity::getPriceByDay, filterComputeDTO.getPrice_by_day_max());
        if (filterComputeDTO.getPrice_by_week_min() != null)
            queryWrapper.ge(ComputeEntity::getPriceByWeek, filterComputeDTO.getPrice_by_week_min());
        if (filterComputeDTO.getPrice_by_week_max() != null)
            queryWrapper.le(ComputeEntity::getPriceByWeek, filterComputeDTO.getPrice_by_week_max());
        if (filterComputeDTO.getPrice_by_month_min() != null)
            queryWrapper.ge(ComputeEntity::getPriceByMonth, filterComputeDTO.getPrice_by_month_min());
        if (filterComputeDTO.getPrice_by_month_max() != null)
            queryWrapper.le(ComputeEntity::getPriceByMonth, filterComputeDTO.getPrice_by_month_max());

        // 其他条件查询
        if (filterComputeDTO.getStatus() != null)
            queryWrapper.eq(ComputeEntity::getStatus, filterComputeDTO.getStatus());
        if (filterComputeDTO.getIs_enable() != null)
            queryWrapper.eq(ComputeEntity::getIsEnable, filterComputeDTO.getIs_enable());
        if (filterComputeDTO.getDescription() != null)
            queryWrapper.like(ComputeEntity::getDescription, filterComputeDTO.getDescription());
        if (filterComputeDTO.getRating() != null)
            queryWrapper.eq(ComputeEntity::getRating, filterComputeDTO.getRating());

        if (filterComputeDTO.getSort() != null) {
            applySorting(queryWrapper, filterComputeDTO.getSort().getCode());
        } else {
            applySorting(queryWrapper, ComputeSortTypeEnum.DEFAULT.getCode());
        }

        // 获取总记录数
        long totalCount = this.count(queryWrapper);
        result.setTotalCount(totalCount);

        // 分页处理
        if (pageSize != null && currentPage != null) {
            IPage<ComputeEntity> page = new Page<>(currentPage, pageSize);
            IPage<ComputeEntity> computePage = page(page, queryWrapper);
            result.setRecords(computePage.getRecords());
        } else {
            result.setRecords(list(queryWrapper));
        }
        return result;
    }

    @Override
    public Boolean enableCompute(String id) {
        ComputeEntity computeEntity = this.getById(id);
        if (computeEntity == null) {
            throw new BusinessException("未找到指定的算力资源");
        }
        if (computeEntity.getIsEnable()) {
            throw new BusinessException("该算力资源已经处于上架状态");
        }
        computeEntity.setIsEnable(true);
        return this.updateById(computeEntity);
    }

    @Override
    public Boolean disableCompute(String id) {
        ComputeEntity computeEntity = this.getById(id);
        if (computeEntity == null) {
            throw new BusinessException("未找到指定的算力资源");
        }
        if (!computeEntity.getIsEnable()) {
            throw new BusinessException("该算力资源已经处于下架状态");
        }
        computeEntity.setIsEnable(false);
        return this.updateById(computeEntity);
    }

    @Override
    public Boolean updateComputeDoc(String id, MultipartFile docFile) {
        ComputeEntity computeEntity = this.getById(id);
        if (computeEntity == null) {
            throw new BusinessException("未找到指定的算力资源");
        }

        if (docFile != null && !docFile.isEmpty()) {
            try {
                // 如果已有文档，先删除旧文档

                String randomString = UUID.randomUUID().toString();
                String newFileName = "compute_helper_document/" + randomString + "_" + docFile.getOriginalFilename();
                String oldDocURL = computeEntity.getDocURL();
                if (oldDocURL != null && !oldDocURL.isEmpty()) {
                    minioUtils.updateFile(oldDocURL, docFile, newFileName);
                    computeEntity.setDocURL(newFileName);
                    return this.updateById(computeEntity);
                } else {
                    // 如果之前没有文档，创建新的文档
                    minioUtils.upload(docFile, newFileName);
                    computeEntity.setDocURL(newFileName);
                    return this.updateById(computeEntity);
                }
            } catch (Exception e) {
                throw new BusinessException("计算资源文档更新失败: " + e.getMessage());
            }
        }
        return false;
    }


    @Override
    public PageReturnResult<ComputeEntity> getHomepageContent(String orderType, Integer currentPage, Integer pageSize, String name) {
        PageReturnResult<ComputeEntity> result = new PageReturnResult<>();
        LambdaQueryWrapper<ComputeEntity> queryWrapper = new LambdaQueryWrapper<>();

        // 只查询已启用的计算资源
        queryWrapper.eq(ComputeEntity::getDelFlag, 0);
        // 只查询非自定义算力
        queryWrapper.eq(ComputeEntity::getIsCustom, false);

        // 应用排序
        applySorting(queryWrapper, orderType);
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(ComputeEntity::getName, name);
        }

        // 获取总记录数
        long totalCount = this.count(queryWrapper);
        result.setTotalCount(totalCount);

        // 分页处理
        if (currentPage != null && pageSize != null) {
            IPage<ComputeEntity> page = new Page<>(currentPage, pageSize);
            IPage<ComputeEntity> computePage = page(page, queryWrapper);
            result.setRecords(computePage.getRecords());
        } else {
            result.setRecords(list(queryWrapper));
        }

        return result;
    }

    private void applySorting(LambdaQueryWrapper<ComputeEntity> queryWrapper, String orderType) {
        ComputeSortTypeEnum.fromCode(orderType).getSortFunction().accept(queryWrapper);
    }

} 